package pers.xiaojun.boot.common.config;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import pers.xiaojun.boot.common.config.properties.CaptchaProperties;
import pers.xiaojun.boot.common.pojo.ImageCaptcha;

/**
 * 验证码配置
 *
 * @author xiaojun
 * @since 2025-10-06
 */
@AutoConfiguration
@EnableConfigurationProperties(CaptchaProperties.class)
@RequiredArgsConstructor
@Slf4j
public class CaptchaAutoConfiguration {

    private final CaptchaProperties captchaProperties;

    /**
     * 验证码生成器
     */
    @Bean
    public CodeGenerator codeGenerator() {
        if (captchaProperties.getType() == CaptchaProperties.Type.RANDOM) {
            if (StrUtil.isBlank(captchaProperties.getBaseChar())) {
                return new RandomGenerator(captchaProperties.getCodeCount());
            }
            return new RandomGenerator(captchaProperties.getBaseChar(), captchaProperties.getCodeCount());
        }
        if (captchaProperties.getType() == CaptchaProperties.Type.MATH) {
            return new MathGenerator(captchaProperties.getNumberLength());
        }
        log.error("验证码生成器创建失败");
        return null;
    }

    /**
     * 图片验证码
     *
     * @param captchaProperties 图片验证码配置
     * @param codeGenerator 验证码生成器
     * @return 图片验证码
     */
    @Bean
    public ImageCaptcha imageCaptcha(CaptchaProperties captchaProperties, CodeGenerator codeGenerator) {
        return new ImageCaptcha(captchaProperties, codeGenerator);
    }
}
